package com.zhiwen.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiwen.common.exception.BusinessException;
import com.zhiwen.domain.entity.User;
import com.zhiwen.domain.entity.UserFollow;
import com.zhiwen.mapper.UserFollowMapper;
import com.zhiwen.service.UserFollowService;
import com.zhiwen.service.UserService;
import com.zhiwen.domain.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户关注服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    private final UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean followUser(Long followUserId) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 不能关注自己
        if (userId.equals(followUserId)) {
            throw new BusinessException("不能关注自己");
        }

        // 检查被关注的用户是否存在
        User followUser = userService.getById(followUserId);
        if (followUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 检查是否已关注
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getUserId, userId);
        wrapper.eq(UserFollow::getFollowUserId, followUserId);
        wrapper.eq(UserFollow::getDeleted, 0);
        UserFollow userFollow = getOne(wrapper);

        if (userFollow != null) {
            // 已经关注过了
            return false;
        }

        // 创建关注记录
        userFollow = new UserFollow();
        userFollow.setUserId(userId);
        userFollow.setFollowUserId(followUserId);
        userFollow.setCreateTime(LocalDateTime.now());
        userFollow.setUpdateTime(LocalDateTime.now());
        userFollow.setDeleted(0);

        return save(userFollow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unfollowUser(Long followUserId) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询关注记录
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getUserId, userId);
        wrapper.eq(UserFollow::getFollowUserId, followUserId);
        wrapper.eq(UserFollow::getDeleted, 0);
        UserFollow userFollow = getOne(wrapper);

        if (userFollow == null) {
            // 未关注过
            return false;
        }

        // 逻辑删除关注记录
        userFollow.setDeleted(1);
        userFollow.setUpdateTime(LocalDateTime.now());

        return updateById(userFollow);
    }

    @Override
    public boolean isFollowed(Long followUserId) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询关注记录
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getUserId, userId);
        wrapper.eq(UserFollow::getFollowUserId, followUserId);
        wrapper.eq(UserFollow::getDeleted, 0);

        return count(wrapper) > 0;
    }

    @Override
    public Page<UserVO> getFollowingList(Long userId, Page<User> page) {
        // 查询关注的用户ID列表
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getUserId, userId);
        wrapper.eq(UserFollow::getDeleted, 0);
        wrapper.orderByDesc(UserFollow::getCreateTime);

        Page<UserFollow> followPage = page(new Page<>(page.getCurrent(), page.getSize()), wrapper);
        List<Long> followUserIds = followPage.getRecords().stream()
                .map(UserFollow::getFollowUserId)
                .collect(Collectors.toList());

        // 构建返回结果
        Page<UserVO> userVOPage = new Page<>();
        userVOPage.setCurrent(followPage.getCurrent());
        userVOPage.setSize(followPage.getSize());
        userVOPage.setTotal(followPage.getTotal());

        // 查询用户信息
        List<UserVO> userVOList = new ArrayList<>();
        if (!followUserIds.isEmpty()) {
            List<User> userList = userService.listByIds(followUserIds);
            userVOList = userList.stream()
                    .map(userService::getUserVO)
                    .collect(Collectors.toList());
        }

        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    public Page<UserVO> getFollowerList(Long userId, Page<User> page) {
        // 查询粉丝用户ID列表
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowUserId, userId);
        wrapper.eq(UserFollow::getDeleted, 0);
        wrapper.orderByDesc(UserFollow::getCreateTime);

        Page<UserFollow> followerPage = page(new Page<>(page.getCurrent(), page.getSize()), wrapper);
        List<Long> followerUserIds = followerPage.getRecords().stream()
                .map(UserFollow::getUserId)
                .collect(Collectors.toList());

        // 构建返回结果
        Page<UserVO> userVOPage = new Page<>();
        userVOPage.setCurrent(followerPage.getCurrent());
        userVOPage.setSize(followerPage.getSize());
        userVOPage.setTotal(followerPage.getTotal());

        // 查询用户信息
        List<UserVO> userVOList = new ArrayList<>();
        if (!followerUserIds.isEmpty()) {
            List<User> userList = userService.listByIds(followerUserIds);
            userVOList = userList.stream()
                    .map(userService::getUserVO)
                    .collect(Collectors.toList());
        }

        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    public List<Long> getFollowingUserIds(Long userId) {
        // 查询用户关注的用户ID列表
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getUserId, userId);
        wrapper.eq(UserFollow::getDeleted, 0);

        // 获取关注记录并提取关注的用户ID
        return list(wrapper).stream()
                .map(UserFollow::getFollowUserId)
                .collect(Collectors.toList());
    }
}
